'
' Twitter Authentication Provider - http://www.oliverhine.com
' Copyright (c) 2009
' by Oliver Hine
'

Imports DotNetNuke.Security.Membership
Imports DotNetNuke.Services.Authentication

Namespace OliverHine.Authentication.Twitter

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' The Login AuthenticationLoginBase is used to provide a login for a registered user
    ''' portal.
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[ohine]	07/14/2009  Created Twitter Authentication Provider
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Public Class Login
        Inherits AuthenticationLoginBase

        Private Const AuthSystemApplicationName As String = "Twitter"

#Region "Protected Properties"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Gets whether the Captcha control is used to validate the login
        ''' </summary>
        ''' <history>
        ''' 	[ohine]	07/14/2009  Created Twitter Authentication Provider
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Protected ReadOnly Property UseCaptcha() As Boolean
            Get
                Return False 'TwitterAuthenticationConfig.GetConfig(PortalId).UseCaptcha
            End Get
        End Property

#End Region

#Region "Public Properties"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Check if the Auth System is Enabled (for the Portal)
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' 	[ohine]	07/14/2009  Created Twitter Authentication Provider
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Overrides ReadOnly Property Enabled() As Boolean
            Get
                Return AuthenticationConfig.GetConfig(PortalId).Enabled
            End Get
        End Property
        Private ReadOnly Property AutoFollow() As Boolean
            Get
                Return AuthenticationConfig.GetConfig(PortalId).AutoFollow
            End Get
        End Property
        Private ReadOnly Property AppUsername() As String
            Get
                Return AuthenticationConfig.GetConfig(PortalId).AppUserName
            End Get
        End Property
        Private ReadOnly Property AutoTweet() As Boolean
            Get
                Return AuthenticationConfig.GetConfig(PortalId).AutoTweet
            End Get
        End Property
        Private ReadOnly Property TweetThis() As String
            Get
                Return AuthenticationConfig.GetConfig(PortalId).TweetThis
            End Get
        End Property

#End Region

#Region "Event Handlers"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' 	[ohine]	07/14/2009  Created Twitter Authentication Provider
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            DotNetNuke.UI.Utilities.ClientAPI.RegisterKeyCapture(Me.Parent, Me.cmdLogin, Asc(vbCr))

            If Not Request.IsAuthenticated Then
                If Page.IsPostBack = False Then
                    Try
                        If Not Request.QueryString("verificationcode") Is Nothing Then
                            If PortalSettings.UserRegistration = PortalRegistrationType.VerifiedRegistration Then
                                'Display Verification Rows 
                                rowVerification1.Visible = True
                                rowVerification2.Visible = True
                                txtVerification.Text = Request.QueryString("verificationcode")
                            End If
                        End If

                    Catch
                        'control not there 
                    End Try
                End If

                If Request("oauth_token") IsNot Nothing Then
                    'should be authenticated now...
                    Dim objTwitterAuth As New oAuthTwitter()

                    objTwitterAuth.AccessTokenGet(Request("oauth_token"))
                    If (objTwitterAuth.TokenSecret.Length > 0) Then
                        Dim url As String = "http://twitter.com/account/verify_credentials.xml"
                        Dim xml As String = objTwitterAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty)


                        Try

                            Dim objXmlDoc As New System.Xml.XmlDocument()
                            objXmlDoc.LoadXml(xml)

                            Dim objId As String = "twitter:" & objXmlDoc.SelectSingleNode("//user//id").InnerText
                            Dim objName As String = objXmlDoc.SelectSingleNode("//user//name").InnerText
                            Dim objUser As String = objXmlDoc.SelectSingleNode("//user//screen_name").InnerText
                            Dim objURL As String = objXmlDoc.SelectSingleNode("//user//url").InnerText


                            If AutoFollow AndAlso AppUsername.Length > 0 Then
                                Try
                                    Dim followxml As String = objTwitterAuth.oAuthWebRequest(oAuthTwitter.Method.POST, String.Format("http://twitter.com/friendships/create/{0}.xml?follow=true", Me.AppUsername), String.Empty)
                                Catch ex As Exception
                                    LogException(ex)
                                End Try
                            End If

                            If AutoTweet AndAlso TweetThis.Length > 0 Then
                                Dim sMessageToTweet = TweetThis
                                If sMessageToTweet.Length > 140 Then sMessageToTweet = TweetThis.Substring(0, 139)
                                Try
                                    objTwitterAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://twitter.com/statuses/update.xml", "status=" + OAuthBase.UrlEncode(sMessageToTweet))
                                Catch ex As Exception
                                    LogException(ex)
                                End Try
                            End If


                            Dim objLoginStatus As DotNetNuke.Security.Membership.UserLoginStatus = UserLoginStatus.LOGIN_FAILURE
                            Dim objUserInfo As Entities.Users.UserInfo = Entities.Users.UserController.ValidateUser(PortalId, objId, "", AuthSystemApplicationName, "", PortalSettings.PortalName, IPAddress, objLoginStatus)


                            'Raise UserAuthenticated Event
                            Dim eventArgs As UserAuthenticatedEventArgs = New UserAuthenticatedEventArgs(objUserInfo, objId, objLoginStatus, AuthSystemApplicationName)
                            eventArgs.AutoRegister = True

                            Dim nvc As New NameValueCollection(2)
                            nvc.Add("NickName", objUser)
                            nvc.Add("DisplayName", objName)

                            eventArgs.Profile = nvc

                            'eventArgs.Authenticated = authenticated
                            'eventArgs.Message = message
                            OnUserAuthenticated(eventArgs)

                        Catch ex As Exception
                            ProcessModuleLoadException(Me, ex)
                        End Try

                    End If
                End If

            End If

            ' trCaptcha1.Visible = UseCaptcha
            ' trCaptcha2.Visible = UseCaptcha

        End Sub

        Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            'txtPassword.Attributes.Add("value", txtPassword.Text)

        End Sub


        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' cmdLogin_Click runs when the login button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        '''     [ohine]	07/14/2009  Created Twitter Authentication Provider
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdLogin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdLogin.Click
            Try
                If (Not UseCaptcha) Then
                    Dim objTwitterAuth As New oAuthTwitter()

                    Response.Redirect(objTwitterAuth.AuthorizationLinkGet()) ' + "&oauth_callback=" & Request.Url.OriginalString)


                End If
            Catch ex As Exception
                'Raise UserAuthenticated Event
                'Dim eventArgs As UserAuthenticatedEventArgs = New UserAuthenticatedEventArgs(objUser, txtUsername.Text, loginStatus, "DNN")
                'eventArgs.Authenticated = authenticated
                'eventArgs.Message = message
                'OnUserAuthenticated(eventArgs)
            End Try


        End Sub


#End Region

    End Class

End Namespace
